package net.piggy.core.executor.simple;

import com.alibaba.fastjson.JSONObject;
import net.piggy.core.executor.Executor;
import net.piggy.core.executor.common.SessionResult;
import net.piggy.core.model.HttpStatement;
import net.piggy.core.util.GatewayConfigUtil;
import net.piggy.core.util.ParamUtil;
import org.apache.dubbo.config.*;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.utils.SimpleReferenceCache;
import org.apache.dubbo.rpc.service.GenericService;

public class DubboExecutor implements Executor {
    public DubboExecutor(){}
    @Override
    public SessionResult execute(HttpStatement httpStatement, JSONObject params) throws Exception {

        ApplicationConfig application = new ApplicationConfig();
        application.setName(httpStatement.getApplicationName());
        application.setQosEnable(false);

        RegistryConfig registry = new RegistryConfig();
        String registryAddress = GatewayConfigUtil.getGatewayConfig().getZookeeperAddress();
        registry.setAddress(registryAddress);


        ConsumerConfig consumer = new ConsumerConfig();
        consumer.setRetries(1);
        consumer.setLoadbalance("roundrobin");

        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setInterface(httpStatement.getInterfaceName());
        reference.setVersion(httpStatement.getInterfaceVersion());
        reference.setGeneric("true");


        DubboBootstrap dubboBootstrap = DubboBootstrap.getInstance();
        dubboBootstrap.application(application).registry(registry).reference(reference).start();

        SimpleReferenceCache cache = SimpleReferenceCache.getCache();
        GenericService genericService = cache.get(reference);

        String methodName = httpStatement.getMethodName();
        String parameterType = httpStatement.getParameterType();
        String parameterName = httpStatement.getParameterName();
        String[] parameterTypeArray = null;
        Object[] parameterValueArray = null;
        if(parameterType!=null && !"".equals(parameterType)) {
            parameterTypeArray = parameterType.split(",");
            parameterValueArray = ParamUtil.getParam(parameterName, params, parameterType);
        }
        Object object = genericService.$invoke(methodName, parameterTypeArray, parameterValueArray);
        return SessionResult.buildSuccess(object);
    }
}
